/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun IoT System Studio
 *                  All rights reserved.
 *
 *       Filename:  database.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2025年04月27日)
 *         Author:  chenhongyu0822@163.com
 *      ChangeLog:  1, Release initial version on "2025年04月27日 16时15分10秒"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>


int insert_data(sqlite3 *db, char *data)
{
	char        *errMsg;
	char        sql[1024];
    char        rpi[50];
	float       temp;
	char        time[50];

    if(sscanf(data, "rpi:%49[^-]--temp:%f--time:%49[^\n]", rpi,&temp,time)!=3)
    {
		printf("Invalid data format!\n");
        return -2;
    }

	snprintf(sql, sizeof(sql), "INSERT INTO temperature(rpi,temp,time) VALUES ('%s','%.2f','%s');",
			rpi, temp, time);

	if(sqlite3_exec(db, sql, 0, 0, &errMsg)!=SQLITE_OK)
	{
		fprintf(stderr, "SQL error:%s\n", errMsg);
		sqlite3_free(errMsg);
		return -3;
	}
	return 0;
}

int database_init(char *file, sqlite3 **db)
{
	char        *zErrMsg=0;
	int         rc;
	char        *sql;

	rc=sqlite3_open(file, db);
	if(rc)
	{
		fprintf(stderr, "Can't open database:%s\n",sqlite3_errmsg(*db));
		return -1;
	}
	else
	{
		fprintf(stderr, "Opened database successfully\n");
	}

	sql="CREATE  TABLE IF NOT EXISTS TEMPERATURE("
		"RPI       TEXT   NOT NULL,"
		"TEMP      REAL   NOT NULL,"
		"TIME      TEXT   NOT NULL);";

	rc=sqlite3_exec(*db, sql, 0, 0, &zErrMsg);
	if(rc!=SQLITE_OK)
	{
		fprintf(stderr,"SQL error:%s\n", zErrMsg);
		sqlite3_free(zErrMsg);
		return -2;
	}
	else
	{
		fprintf(stdout, "Table created successfully!\n");
	}
	return 0;
} 


